package com.ruiysoft.crm.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruiysoft.crm.mapper.SysUserMapper;
import com.ruiysoft.crm.model.entity.SysUser;
import com.ruiysoft.crm.model.vo.UserGroupByDeptVo;
import com.ruiysoft.crm.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author liuht
 * @date 2017/10/31
 */
@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private SysUserMapper sysUserMapper;

    public SysUserServiceImpl(SysUserMapper sysUserMapper) {
        this.sysUserMapper = sysUserMapper;
    }

    @Override
    public List getUsersByDept() {
        List<UserGroupByDeptVo> userGroupByDeptVoList = sysUserMapper.getUsersByDept();
        Map<Integer, List<UserGroupByDeptVo>> userGroupDept = userGroupByDeptVoList.stream().collect(Collectors.groupingBy(UserGroupByDeptVo::getDeptId, Collectors.toList()));

        Map<Integer, List<UserGroupByDeptVo>> sortMap = new TreeMap<>(new MapKeyComparator());
        sortMap.putAll(userGroupDept);

        List result = new ArrayList();
        sortMap.forEach((key, value) -> {
            Map<String, Object> deptWithUser = new HashMap<>();
            deptWithUser.put("label", value.get(0).getDeptName());
            List users = new ArrayList();
            value.forEach(userGroupByDeptVo -> {
                Map<String, Object> user = new HashMap<>(16);
                user.put("value", userGroupByDeptVo.getUserId());
                user.put("label", userGroupByDeptVo.getRealName());
                users.add(user);
            });
            deptWithUser.put("options", users);
            result.add(deptWithUser);
        });

        return result;
    }

    @Override
    public int getUserIdByUserName(String userName) {
        if (StringUtils.isEmpty(userName)) {
            return 0;
        }
        return sysUserMapper.getUserIdByUserName(userName);
    }

    class MapKeyComparator implements Comparator<Integer> {

        @Override
        public int compare(Integer key1, Integer key2) {
            return key1.compareTo(key2);
        }
    }
}
